import Node from './node';
import { getuuId } from './utils/uuid'

interface OptionsTyp {
  data: Record<string, any>[]
}

/**
 * Creates a new Tree.
 * @class
 * @param{ ids } 唯一id 列表
 */
export default class Tree {
  ids: string[];
  tree: Record<string, any>[];
  constructor(options: OptionsTyp) {
    this.tree = [];
    this.ids = [];
    if (options.data.length > 0) {
      this.generateTree(options.data)
    }
  }
  generateTree(data) {
    data.forEach((item, index) => {
      const node = new Node({
        ids: this.ids,
        name: item.label,
        children: item.children,
        id: getuuId(this.ids),
        index: '1',
        parentId: null,
        parentIndex: null,
        rootNode: true,
        level: 1,
        className: item.className,
        customContent: item.customContent
      })
      this.tree.push(node)
    });
  }

  removeChild(node) {
    // 根节点不允许删
    if (node.rootNode) {
      return false;
    }
    const parentIndex = node.parentIndex;
    let parentLevel = node.level - 1;
    const indexArr = parentIndex.split("-").map(index => Number(index) - 1);
    const parentNode = indexArr.reduce((acc, cur) => {
      parentLevel -= 1;
      if (acc[cur].children.length > 0) {
        return parentLevel === 0 ? acc[cur] : acc[cur].children;
      }
    }, this.tree);
    const deletIndex = parentNode.children.findIndex(item => item.id === node.id);
    parentNode.children.splice(deletIndex, 1);
    return 'remove'
  }

  addChild(node) {
    const nodeIndex = `${node.index}-${node.children.length + 1}`;
    const level = node.level + 1;
    const newNode = new Node({
      name: '新增节点',
      rootNode: false,
      children: [],
      id: getuuId(this.ids),
      index: nodeIndex,
      parentId: node.id,
      parentIndex: node.index,
      level: level,
      expanded: false,
      focus: true
    })
    node.children.push(newNode);
  }
}

